
const { get, post, put, controller, Auth, del } = require('../lib/decorator')
import {
  getAllMovies,
  getSingleMovie,
  getRelativeMovies,
  getMoviesList,
  deleteMovie
} from '../service/movie'

import {
  saveVisitor
} from '../service/visitor'

@controller('/api/v0/movies')
export class movieController {
  @get('/')
  async getMovies (ctx, next) {
    let type = ctx.query.type
    let year = ctx.query.year
    let pageSize = ctx.query.pageSize
    let pageNum = ctx.query.pageNum

    let { movies, count } = await getAllMovies(type, year, pageSize, pageNum)
    ctx.body = {
      data: movies,
      count,
      username: ctx.session.user && (ctx.session.user.username || '游客') || '游客',
      success: true
    }
  }
  @get('/visit')
  async visit(ctx, next) {
    // console.log(ctx.query, '11111111111111111111111')
    const status = await saveVisitor(ctx.query)
    ctx.body = status
  }
  @get('/:id')
  async  getMovieDetail (ctx, next) {
    const id = ctx.params.id
    const movie = await getSingleMovie(id)
    const relativeMovies = await getRelativeMovies(movie)

    ctx.body = {
      data: {
        movie,
        relativeMovies
      },
      success: true
    }
  }

}


@controller('/api/v0/moviesList')
export class movieListController {
  @get('/')
  @Auth
  async getMovies(ctx, next) {
    let pageSize = ctx.query.pageSize
    let pageNum = ctx.query.pageNum

    let { movies, count } = await getMoviesList(pageSize, pageNum)
    ctx.body = {
      data: movies,
      count,
      username: ctx.session.user.username,
      success: true
    }
  }

  @del('/delete')
  @Auth
  async deleteMovie(ctx, next) {
    let _id = ctx.query._id
    if (ctx.session.user.role !== 'superAdmin') {
      return (ctx.body = {
        success: false,
        message: '你还不是超级管理员权限，不能删除数据'
      })
    }
    let { deletedCount } = await deleteMovie(_id)
    if (deletedCount === 1) {
      return (ctx.body = {
        success: true,
        message: '删除成功'
      })
    }
  }
}